package com.qdxwx.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Http工具类
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static CloseableHttpClient httpClientSSL;

    public static CloseableHttpClient getHttpClient() {
        if (httpClientSSL != null) return httpClientSSL;
        try {
            //https config
            TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
            SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext
                    , null, null, NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", csf)
                    .build();

            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
            //最大连接数300
            connectionManager.setMaxTotal(3000);
            //路由链接数30
            connectionManager.setDefaultMaxPerRoute(100);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(3000)
                    .setConnectTimeout(3000)
                    .setConnectionRequestTimeout(3000)
                    .build();

            httpClientSSL = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                    .setConnectionManager(connectionManager)
                    .evictExpiredConnections()
                    .evictIdleConnections(30, TimeUnit.SECONDS)
                    .build();
            //HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            //requestFactory.setHttpClient(httpClient);
            //return new RestTemplate(requestFactory);
            return httpClientSSL;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static String doGet(String url) {
        return doGet(url, null, null);
    }

    public static String doGet(String url, Map<String, String> queryMap) {
        return doGet(url, queryMap, null);
    }

    public static String doGet(String url, Map<String, String> queryMap, Map<String, String> headerMap) {

        HttpGet request = new HttpGet(buildUrl(url, queryMap));
        if (headerMap != null) {
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        try {
            CloseableHttpResponse httpResponse = getHttpClient().execute(request);
            if (httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                String resp = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                return resp;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }

    public static String doPost(String url, Map<String, String> queryMap) {
        return doPost(url, queryMap, null);
    }

    /**
     * post form
     *
     * @param url       地址
     * @param queryMap  参数
     * @param headerMap 头
     * @return CloseableHttpResponse
     */

    public static String doPost(String url, Map<String, String> queryMap, Map<String, String> headerMap) {

        try {
            HttpPost request = new HttpPost(url);
            if (headerMap != null) {
                for (Map.Entry<String, String> header : headerMap.entrySet()) {
                    request.addHeader(header.getKey(), header.getValue());
                }
            }
            if (queryMap != null) {
                List<NameValuePair> pairs = new ArrayList<>();
                for (Map.Entry<String, String> query : queryMap.entrySet()) {
                    pairs.add(new BasicNameValuePair(query.getKey(), query.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
                formEntity.setContentType("application/x-www-form-urlencoded; charset=utf-8");
                request.setEntity(formEntity);
            }
            CloseableHttpResponse httpResponse = getHttpClient().execute(request);
            if (httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                String resp = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                return resp;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }

    public static String doPost(String url, String queryString) throws Exception {
        return doPost(url, queryString, null);
    }

    /**
     * Post String
     *
     * @param url         地址
     * @param queryString 参数
     * @param headerMap   头
     * @return CloseableHttpResponse
     */

    public static String doPost(String url, String queryString, Map<String, String> headerMap) {
        HttpPost request = new HttpPost(url);
        if (headerMap != null) {
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        if (queryString != null) {
            request.setEntity(new StringEntity(queryString, "utf-8"));
        }
        try {
            CloseableHttpResponse httpResponse = getHttpClient().execute(request);
            if (httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                String resp = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                return resp;
            }
        } catch (Exception ex) {
            System.out.println("error:" + ex.getMessage());
        }
        return null;
    }

    /**
     * Put String
     *
     * @param url       地址
     * @param queryMap  参数
     * @param headerMap 头
     * @return CloseableHttpResponse
     */
    public String doPut(String url, Map<String, String> queryMap, Map<String, String> headerMap) {
        HttpPut request = new HttpPut(url);
        if (headerMap != null) {
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        if (queryMap != null) {
            request.setEntity(new StringEntity(toQueryString(queryMap), "utf-8"));
        }
        try {
            CloseableHttpResponse httpResponse = getHttpClient().execute(request);
            if (httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                String resp = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                return resp;
            }
        } catch (Exception ex) {
            System.out.println("error:" + ex.getMessage());
        }
        return null;
    }

    /**
     * Delete
     *
     * @param url         地址
     * @param queryString 参数
     * @param headerMap   头
     * @return CloseableHttpResponse
     */
    public static String doDelete(String url, String queryString, Map<String, String> headerMap) {
        HttpDelete request = new HttpDelete(buildUrl(url, queryString));
        if (headerMap != null) {
            for (Map.Entry<String, String> header : headerMap.entrySet()) {
                request.addHeader(header.getKey(), header.getValue());
            }
        }
        try {
            CloseableHttpResponse httpResponse = getHttpClient().execute(request);
            if (httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                String resp = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                return resp;
            }
        } catch (Exception ex) {
            System.out.println("error:" + ex.getMessage());
        }
        return null;
    }

    public static String buildUrl(String url, Map<String, String> queryMap) {
        return buildUrl(url, toQueryString(queryMap));
    }

    public static String buildUrl(String url, String queryString) {
        StringBuilder sbUrl = new StringBuilder(url);
        if (null != queryString) {
            if (queryString.substring(0, 1).contains("&")) {
                queryString = queryString.substring(1);
            }
            sbUrl.append("?").append(queryString);
        }
        return sbUrl.toString();
    }

    public static String toQueryString(Map<String, String> queryMap) {
        if (null == queryMap) return null;
        StringBuilder sbQuery = new StringBuilder();
        for (Map.Entry<String, String> query : queryMap.entrySet()) {
            if (0 < sbQuery.length()) {
                sbQuery.append("&");
            }
            sbQuery.append(query.getKey());
            sbQuery.append("=");
            sbQuery.append(query.getValue());
        }
        return sbQuery.toString();
    }
}

